package com.nhim.cms.admin.client.template.ui;

import java.util.List;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.HasKeyboardPagingPolicy.KeyboardPagingPolicy;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.nhim.cms.admin.client.ScrollablePagerPanel;
import com.nhim.cms.admin.client.place.ContentTemplateListPlace;
import com.nhim.cms.admin.client.rpc.TemplateRPCService;
import com.nhim.cms.admin.client.rpc.TemplateRPCServiceAsync;
import com.nhim.cms.admin.client.template.ui.TemplateEditPopup.Listener;
import com.nhim.cms.admin.shared.ETemplateType;
import com.nhim.cms.admin.shared.NhimCMSAdminRequestFactory;
import com.nhim.cms.admin.shared.TemplateRPCProxy;

public class TemplateList extends Composite implements Activity {

	private static ContentTemplateListUiBinder uiBinder = GWT
			.create(ContentTemplateListUiBinder.class);

	interface ContentTemplateListUiBinder extends
			UiBinder<Widget, TemplateList> {
	}

	public TemplateList() {
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	TemplateRPCProxy selectedTemplate;

	/**
	 * The CellList.
	 */
	private CellList<TemplateRPCProxy> templateCellList;
	// Add a selection model so we can select cells.
	SingleSelectionModel<TemplateRPCProxy> tempalteSelectionModel = new SingleSelectionModel<TemplateRPCProxy>(
			TEMPLATE_KEY_PROVIDER);

	private ListDataProvider<TemplateRPCProxy> templateDataProvider = new ListDataProvider<TemplateRPCProxy>();

	/**
	 * The key provider that provides the unique ID of a contentType.
	 */
	public static final ProvidesKey<TemplateRPCProxy> TEMPLATE_KEY_PROVIDER = new ProvidesKey<TemplateRPCProxy>() {
		public Object getKey(TemplateRPCProxy item) {
			return item == null ? null : item.getId();
		}
	};
	private final TemplateRPCServiceAsync service = GWT.create(TemplateRPCService.class);
	@UiField
	Button btnNew;
	@UiField
	Button btnEdit;
	@UiField
	Button btnDelete;
	@UiField
	ScrollablePagerPanel pagerPanel;
	private ETemplateType type;
	private Integer contentTypeId;
	TemplateEditPopup popup;
	public TemplateList(NhimCMSAdminRequestFactory requestFactory) {
		initWidget(uiBinder.createAndBindUi(this));
		popup = new TemplateEditPopup();

	}

	public String mayStop() {

		return null;
	}

	public void onCancel() {

	}

	public void onStop() {

	}

	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		panel.setWidget(this);
		
	}

	public void updateForPlace(final ContentTemplateListPlace place) {
		btnDelete.setVisible(false);
		String[] temp = place.getToken().split("!")[1].split("#");
		if (temp.length > 1) {
			selectedTemplate = null;
			type = ETemplateType.get(Integer.parseInt(temp[0])); 
			contentTypeId = Integer.parseInt(temp[1]);
			// Create a CellList.
			TemplateCell templateList = new TemplateCell();
			
			templateCellList = new CellList<TemplateRPCProxy>(templateList,
					TEMPLATE_KEY_PROVIDER);
			templateCellList.setPageSize(30);
			templateCellList
					.setKeyboardPagingPolicy(KeyboardPagingPolicy.INCREASE_RANGE);
			templateCellList
					.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.BOUND_TO_SELECTION);
	

			templateCellList.setSelectionModel(tempalteSelectionModel);
			tempalteSelectionModel
					.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
						public void onSelectionChange(SelectionChangeEvent event) {	
							selectedTemplate =  tempalteSelectionModel.getSelectedObject();
							btnDelete.setVisible(true);
						}
					});
			
			pagerPanel.setDisplay(templateCellList);
			templateDataProvider.addDataDisplay(templateCellList);
			rebindTemplate();

		}
	}
	final List<TemplateRPCProxy> data = templateDataProvider.getList();
	AsyncCallback<List<TemplateRPCProxy>> asynResult = new AsyncCallback<List<TemplateRPCProxy>>(){
		
		@Override
		public void onFailure(Throwable error) {
			Window.alert(error.getMessage());
			
		}

		@Override
		public void onSuccess(List<TemplateRPCProxy> result) {
			
			for(TemplateRPCProxy proxy : result)
			{
				data.add(proxy);
			}
			
		}};
	private void rebindTemplate() {
		
		data.clear();
		switch (type) {
		case GROUP_TEMPLATE:
			service.findAllGroupTemplate(asynResult);
			break;
		case SITE_TEMPLATE:
			service.findAllSiteTemplate(asynResult);
			break;
		case CONTENT_TEMPLATE:
			service.findAllContentTemplateTemplate(contentTypeId, asynResult);
			break;
		}
		
		templateCellList.redraw();
	
	}
	private void showPopup(TemplateRPCProxy template)
	{	
		popup.SetData(template,type,contentTypeId);
		popup.setGlassEnabled(true);
		popup.center();
		popup.setListener(new Listener(){

			@Override
			public void onSave() {			
				rebindTemplate();
			}});
		
	}

	@UiHandler("btnNew")
	void handleButtonNewClick(ClickEvent e) {
		
		showPopup(null);
	}
	@UiHandler("btnEdit")
	void handleButtonEditClick(ClickEvent e) {
		if(selectedTemplate != null)
			showPopup(selectedTemplate);
	}
	@UiHandler("btnDelete")
	void handleButtonDeleteClick(ClickEvent e) {
		if(selectedTemplate != null)
		{
			if (Window.confirm("Are you sure you want to delete this template?")) {
				service.remove(selectedTemplate.getId(), new AsyncCallback<Boolean>(){

					@Override
					public void onFailure(Throwable error) {
						Window.alert(error.getMessage());
						
					}

					@Override
					public void onSuccess(Boolean result) {
						if(result)
						{
							rebindTemplate();
							selectedTemplate = null;
						}
						
					}});
			}

		}
	}

	/**
	 * The Cell used to render a {@link GroupCell}.
	 */
	static class TemplateCell extends AbstractCell<TemplateRPCProxy> {

		public TemplateCell() {

		}

		@Override
		public void render(com.google.gwt.cell.client.Cell.Context arg0,
				TemplateRPCProxy value, SafeHtmlBuilder sb) {

			// Value can be null, so do a null check..
			if (value == null) {
				return;
			}

			sb.appendHtmlConstant("<table>");

			// Add the content type image.
			sb.appendHtmlConstant("<tr>");

			// Add the name and description.
			sb.appendHtmlConstant("<td style='font-size:95%;'>");
			sb.appendEscaped(value.getName());
			sb.appendHtmlConstant("</td></tr></table>");
		}

	}

}
